<?php


namespace app\home\controller;


use app\base\BaseController;
use app\home\validate\ProcessReport;
use think\Exception;
use think\facade\Db;
use think\facade\View;

/**
 * Class ProcessReporting
 * @package app\home\controller
 * 工序报工
 */
class ProcessReporting extends BaseController
{
    protected $table='process_reporting';
    protected $title='工序报工';
    private $sessionKey='pageProcessReporting';
    protected $pricingMode=[
        '个人',
        '班组'
    ];
    public function index()
    {
        $param=$this->param;
        if (request()->isAjax()) {

            $where[]=['status','>',-1];
            foreach (['status','id','pricing_mode']as $v){
                if (isset($param[$v])&&$param[$v]){
                    $where[]=[$v,'=',$param[$v]];
                }
            }
            foreach (['bar_code','mdName','circulationNum','specs','craftName'] as $i){
                if (isset($param[$i])&&$param[$i]){
                    $where[]=[$i,'like','%'.$param[$i].'%'];
                }
            }
            if (isset($param['u_g_name'])&&$param['u_g_name']){
                if ($param['pricing_mode']=='个人'){
                    $where[]=['username','like','%'.$param['u_g_name'].'%'];
                }else if ($param['pricing_mode']=='班组'){
                    $where[]=['teamName','like','%'.$param['u_g_name'].'%'];
                }

            }
            if (isset($param['orderDate'])&&$param['orderDate']){
                $times=explode('~',$param['orderDate']);
                $where[]=['orderDate','between',$times];
            }
            session($this->sessionKey,$where);
            $rows = empty($param['limit']) ? get_config('app.page_size') : $param['limit'];
            $list = Db::name('process_report_view')
                ->where($where)
                ->order('id desc')
                ->paginate($rows);
            return table_assign(0, '', $list);
        } else {
            return view();
        }

    }
    public function add()
    {
        $param = get_params();
        if (request()->isAjax()) {
            $param=$this->param;
            Db::startTrans();
            $param['update_time']=time();
            $validate=new ProcessReport();
            if (!$validate->scene('processReport')->check($this->param)){
                return to_assign(1,'参数不能为空');
            }
            $id=$param['id']??0;
            try {
                if ($param['id'] > 0) {
                    Db::name($this->table)->strict(false)->field(true)->update($param);
                    add_log('edit', $param['id'], $param,$this->title);
                } else {
                    $param['create_time'] = time();
                    $id = Db::name($this->table)->strict(false)->field(true)->insertGetId($param);
                    add_log('add', $id, $param,$this->title);
                }
                Db::commit();
            }catch (\Exception $e){
                Db::rollback();
                return to_assign(1,'操作失败:'.$e->getMessage());
            }

            return to_assign();
        } else {
            $id = isset($param['id']) ? $param['id'] : 0;
            if ($id > 0) {
                $detail = Db::name($this->table)->where('id', $id)->find();
                View::assign('detail', $detail);
            }
            $planList=Db::name('production_plan')->where('status',3)->field('circulationNum ,id')->select();
            View::assign('pricingMode',$this->pricingMode);
            View::assign('id', $id);
            View::assign('planList', $planList);
            View::assign('defalutTime', date('Y-m-d'));
            return view('form');
        }
    }

    public function confirm()
    {
        $id=$this->param['id']??0;
        if (!$id){
            return to_assign(1,'参数缺失');
        }
        try {
            Db::name($this->table)->where('id',$id)->update(['checkUser'=>$this->uid,'status'=>2,'update_time'=>time(),'confirmTime'=>time()]);
            add_log('apply', $id, $this->param,$this->title);
        }catch (\Exception $e){
            return to_assign(1,'操作失败:'.$e->getMessage());
        }
        return to_assign(0,'操作成功');
    }
    /**
     * date:2024/4/18
     * 确认
     */
    public function onSure()
    {
        $res=\app\home\severs\ProcessReporting::onSure($this->param,$this->uid);
        return to_assign($res['code'],$res['msg']);
    }

    public function onCancel()
    {
        $res=\app\home\severs\ProcessReporting::onCancel($this->param,$this->uid);
        return to_assign($res['code'],$res['msg']);
    }
    /**
     * @return \json
     * @throws \think\db\exception\DbException
     * date:2024/3/21
     * 删除
     */
    public function delete()
    {
        if (request()->isDelete()) {
            $id = get_params("id");
            $status=Db::name($this->table)->where('id','in',$id)->column('status');
            if (in_array('3',$status)){
                return  to_assign(1, "有已确认数据，不能删除");
            }
            try {
                Db::name($this->table)->where('id','in',$id)->update(['status'=>-1,'deleted'=>time()]);
                add_log('delete', $id, request()->param(),$this->title);
            }catch (\Exception $e){
                return to_assign(1, "删除失败".$e->getMessage());
            }
            return to_assign(0, "删除成功");
        } else {
            return to_assign(1, "错误的请求");
        }
    }

    public function exportData()
    {
        $where=session($this->sessionKey);
        $mStatus=['','草稿','待确认','已确认'];
        $list = Db::name('process_report_view')
            ->where($where)
            ->order('id desc')
            ->select()
            ->each(function ($item) use ($mStatus){
                $item['status']=$mStatus[$item['status']];
                $item['u_g_name']=$item['pricing_mode']=='个人'?$item['username']:$item['teamName'];
                return $item;
            });
        $title = [
            'id' => 'ID',
            'circulationNum' => '关联源单',
            'craftName' => '工序',
            'pricing_mode' => '计价方式',
            'u_g_name' => '班组/个人',
            'bar_code' => '物料编码',
            'mdName' => '物料名称',
            'specs' => '规格型号',
            'unit' => '单位',
            'qualifiedNum' => '合格品数量',
            'passNum' => '工废数量',
            'wasteNum' => '废料数量',
            'orderDate' => '单据日期',
            'status' => '状态',
        ];
        $name =$this->title;
        exportXlsData($name,$title,$list);
        exit();
    }
}